/*
 * 文件名：MainPageController.java
 * 版权：Copyright by hlst
 * 描述：
 * 修改人：liuziyu
 * 修改时间：2016年7月19日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package com.zcsy.manage.shop.controller.mainPage;

import java.io.File;
import java.io.FileNotFoundException;
import java.math.BigDecimal;
import java.sql.Time;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.ObjectMetadata;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.constants.ShopConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.commons.upload.AliyunOssUtil;
import com.zcsy.commons.upload.FileUploadUtil;
import com.zcsy.commons.upload.FileUploadUtil.UploadFileItem;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.commons.util.PropertiesUtil;
import com.zcsy.manage.model.base.CommonToken;
import com.zcsy.manage.model.base.ShopInfo;
import com.zcsy.manage.model.mall.CouponDetail;
import com.zcsy.manage.model.mall.CouponInfo;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.service.base.IShopInfoService;
import com.zcsy.manage.service.mall.ICouponDetailService;
import com.zcsy.manage.service.mall.ICouponInfoService;
import com.zcsy.manage.service.mall.IOrderInfoService;
import com.zcsy.manage.service.system.IUserService;
import com.zcsy.manage.shop.service.system.ICommonTokenService;

@Controller
@RequestMapping(value = "/shopMainPage")
public class MainPageController {

	@Autowired
	private IShopInfoService shopInfoService;
	
	@Autowired
	private IOrderInfoService orderInfoService;
	
	@Autowired
	private ICouponInfoService couponInfoService;
	
	@Autowired
	private ICommonTokenService commonTokenService;
	
	@Autowired
	private ICouponDetailService couponDetailService;
	
	@Autowired
    private IUserService userService;
	
	private static PropertiesUtil propertiesUtil=new PropertiesUtil("config.properties");
    private static String endpoint = propertiesUtil.getProperty("OSS_ENDPOINT");
    private static String accessId= propertiesUtil.getProperty("ACCESS_ID");
    private static String accessKey= propertiesUtil.getProperty("ACCESS_KEY");
    private static String bucketName= propertiesUtil.getProperty("bucketName");
	/**
	 * @Method: getShopList
	 * @Description 获取店铺列表
	 * @param token
	 * @param shopId 店铺id字符串
	 * @return 
	 * @author liuziyu liuziyuwri@foxmail.com
	 * @date 2016年7月19日
	 * @see 
	 */
	@RequestMapping(value = "getShopList")
	@ResponseBody
	public RequestJson getShopList(String token, String shopId) {
		RequestJson result = new RequestJson();
		List<ShopInfo> shopInfos = new ArrayList<ShopInfo>();
		boolean flag = false;

		// 将shopId字符串根据“，”分开
		String[] shopIdArray = shopId.split(",");
		for (String shopIdSingle : shopIdArray) {
			shopInfos.add(shopInfoService.selectByPrimaryKey(shopIdSingle));
		}

		// 判断读取的数据是否为空
		Iterator<ShopInfo> iterator = shopInfos.iterator();
		while (iterator.hasNext()) {
			ShopInfo ShopInfoSingle = (ShopInfo) iterator.next();
			if (ShopInfoSingle == null) {
				flag = false;
				break;
			} else {
				flag = true;
			}
		}
		if (!flag) {
			result.setSuccess(false);
			result.setResultCode(ShopConstants.RESULT_CODE_FALSE);
			result.setMsg("未找到全部店铺信息！");
		} else {
			result.setSuccess(true);
			result.setResultCode(ShopConstants.RESULT_CODE_SUCCESS);
			result.setMsg("所有店铺信息读取成功！");
			result.setObj(shopInfos);
		}
		return result;
	}
	
	/**
	 * @Method: getOrderSum
	 * @Description 查询首页订单数量汇总
	 * @param token
	 * @param shopId 店铺id
	 * @return 
	 * @author liuziyu liuziyuwri@foxmail.com
	 * @date 2016年7月19日
	 * @see 
	 */
	@RequestMapping(value = "getOrderSum")
	@ResponseBody
	public RequestJson getOrderSum(String token, String shopId) {
		RequestJson result = new RequestJson();
		
		try {
			// 查询待支付订单数量
			Map<String, Object> notPayMap = new HashMap<String, Object>();
			notPayMap.put("shopId", shopId);
			notPayMap.put("state", ShopConstants.ORDER_STATE_NOT_PAY);
			Integer notPayInteger = orderInfoService.getShopOrderSum(notPayMap);
			
			// 查询待确认订单数量
			Map<String, Object> notConfirmMap = new HashMap<String, Object>();
			notConfirmMap.put("shopId", shopId);
			notConfirmMap.put("state", ShopConstants.ORDER_STATE_NOT_CONFIRM);
			Integer notConfirmInteger = orderInfoService.getShopOrderSum(notConfirmMap);
			
			// 查询待发货订单数量
			Map<String, Object> notSendMap = new HashMap<String, Object>();
			notSendMap.put("shopId", shopId);
			notSendMap.put("state", ShopConstants.ORDER_STATE_NOT_SEND);
			Integer notSendInteger = orderInfoService.getShopOrderSum(notSendMap);
			
			// 查询售后订单数量（退款退货）
			Map<String, Object> refundMap = new HashMap<String, Object>();
			refundMap.put("shopId", shopId);
			refundMap.put("state", ShopConstants.ORDER_STATE_REFUND);
			Integer refundInteger = orderInfoService.getShopOrderSum(refundMap);
			Map<String, Object> returnGoodsMap = new HashMap<String, Object>();
			returnGoodsMap.put("shopId", shopId);
			returnGoodsMap.put("state", ShopConstants.ORDER_STATE_RETURN_GOODS);
			Integer returnGoodsInteger = orderInfoService.getShopOrderSum(returnGoodsMap);
			Map<String, Object> sumMap = new HashMap<String, Object>();
			
			sumMap.put("notPay", notPayInteger);
			sumMap.put("notConfirm", notConfirmInteger);
			sumMap.put("notSend", notSendInteger);
			sumMap.put("afterSale", refundInteger + returnGoodsInteger);
			result.setObj(sumMap);
			result.setSuccess(true);
			result.setResultCode(ShopConstants.RESULT_CODE_SUCCESS);
			result.setMsg("查询订单数量成功！");
			
		} catch (Exception e) {
			result.setSuccess(false);
			result.setResultCode(ShopConstants.RESULT_CODE_FALSE);
			result.setMsg("查询订单数量失败！");
		}
		return result;
	}
	
	/**
	 * @Method: changeShopInfo
	 * @Description 店铺信息变更
	 * @param token
	 * @param shopId 店铺id
	 * @param logo 店铺logo
	 * @param name 店铺名称
	 * @param beginTime 营业起始时间
	 * @param endTime 营业结束时间
	 * @param state 营业状态
	 * @param phone 电话1
	 * @param phone2 电话2
	 * @param address 地址
	 * @param descrip 店铺描述
	 * @return 
	 * @author liuziyu liuziyuwri@foxmail.com
	 * @date 2016年7月20日
	 * @see 
	 */
	@RequestMapping(value = "changeShopInfo")
	@ResponseBody
	public RequestJson changeShopInfo(String token, String shopId,
			String name, String beginTime, String endTime, String phone,
			Integer state, String phone2, String address, String descrip) {
		RequestJson result = new RequestJson();

		ShopInfo record = shopInfoService.selectByPrimaryKey(shopId);
		Time begin = null;
		Time end = null;
		try {
			DateFormat sdf = new SimpleDateFormat("hh:mm");
			// 将String时间转换为Time
			if (beginTime != null) {
				Date dateBegin = sdf.parse(beginTime);
				begin = new Time(dateBegin.getTime());
				record.setBeginTime(begin);
				
			}
			if (endTime != null) {
				Date dateEnd = sdf.parse(endTime);
				end = new Time(dateEnd.getTime());
				record.setEndTime(end);
				
			}
			record.setState(state);
			record.setId(shopId);
			record.setName(name);
			record.setPhone(phone);
			record.setPhone2(phone2);
			record.setAddress(address);
			record.setDescrip(descrip);
			int updateState = shopInfoService.update(record);
			if (updateState == ShopConstants.STATE_SUCCESS) {
				result.setObj(record);
				result.setSuccess(true);
				result.setResultCode(ShopConstants.RESULT_CODE_SUCCESS);
				result.setMsg("店铺信息变更成功！");

			} else {
				result.setSuccess(false);
				result.setResultCode(ShopConstants.RESULT_CODE_FALSE);
				result.setMsg("店铺信息变更失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			result.setResultCode(ShopConstants.RESULT_CODE_FALSE);
			result.setMsg("营业时间格式不对！");
		}

		return result;
	}
	
	/**
	 * @Method: getCouponList
	 * @Description 优惠券列表（查询条件：未开始，进行中，已失效）
	 * @param token
	 * @param pNo 分页
	 * @param shopId 店铺id
	 * @param state 优惠券状态（1未开始，2进行中，3已失效）
	 * @return 
	 * @author liuziyu liuziyuwri@foxmail.com
	 * @date 2016年7月21日
	 * @see 
	 */
	@RequestMapping(value = "getCouponList")
	@ResponseBody
	public RequestJson getCouponList(String token, String shopId,
			Integer state, Integer pNo) {
		RequestJson result = new RequestJson();

		// 指定默认为首页
		if (pNo == null || pNo < ShopConstants.PAGE_NO) {
			pNo = ShopConstants.PAGE_NO;
		}

		if (state != ShopConstants.COUPON_STATE_NOT_START && state != ShopConstants.COUPON_STATE_UNDERWAY && state != ShopConstants.COUPON_STATE_INVALID) {
			result.setSuccess(false);
			result.setResultCode(ShopConstants.RESULT_CODE_FALSE);
			result.setMsg("state入参有误！");
		}else {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("shopId", shopId);
			map.put("state", state);
			
			// 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
			PageHelper.startPage(pNo, ShopConstants.PAGE_SIZE);
			
			List<CouponInfo> allCouponInfos = couponInfoService
					.getAllCouponInfoByShopId(map);
			
			if (allCouponInfos.isEmpty()) {
				result.setSuccess(false);
				result.setResultCode(ShopConstants.RESULT_CODE_FALSE);
				result.setMsg("未查询到优惠券！");
			} else {
				// 分页
				PageInfo<CouponInfo> stateCouponInfosP = new PageInfo<CouponInfo>(
						allCouponInfos);
				result.setObj(stateCouponInfosP);
				result.setSuccess(true);
				result.setResultCode(ShopConstants.RESULT_CODE_SUCCESS);
				result.setMsg("成功获取优惠券！");
			}
		}
		
		return result;
	}
	
	/**
	 * @Method: setCouponAbleDisable
	 * @Description  优惠券启用、禁用 
	 * @param token
	 * @param couponId 优惠券id
	 * @return 
	 * @author liuziyu liuziyuwri@foxmail.com
	 * @date 2016年7月21日
	 * @see 
	 */
	@RequestMapping(value = "setCouponAbleDisable")
	@ResponseBody
	public RequestJson setCouponAbleDisable(String token, String couponId) {
		RequestJson result = new RequestJson();

		// 在数据库查询状态
		CouponInfo couponInfo = couponInfoService.selectByPrimaryKey(couponId);
		if (couponInfo != null) {
			Integer nowState = couponInfo.getState();
			// 如果已经是正常状态，操作为禁用
			if (nowState == ShopConstants.COUPON_STATE_NOMAL) {
				CouponInfo set = new CouponInfo();
				set.setId(couponId);
				set.setState(ShopConstants.COUPON_STATE_SHOP_FORBIDDEN);
				Integer stateInteger = couponInfoService.update(set);
				if (stateInteger == ShopConstants.STATE_SUCCESS) {
					result.setObj(set);
					result.setSuccess(true);
					result.setResultCode(ShopConstants.RESULT_CODE_SUCCESS);
					result.setMsg("成功更改优惠券状态！");
				} else {
					result.setSuccess(false);
					result.setResultCode(ShopConstants.RESULT_CODE_FALSE);
					result.setMsg("改变状态失败！");

				}

				// 如果已经是禁用状态，操作为启用
			} else if (nowState == ShopConstants.COUPON_STATE_SHOP_FORBIDDEN) {
				CouponInfo set = new CouponInfo();
				set.setId(couponId);
				set.setState(ShopConstants.COUPON_STATE_NOMAL);
				Integer stateInteger = couponInfoService.update(set);
				if (stateInteger == ShopConstants.STATE_SUCCESS) {
					result.setObj(set);
					result.setSuccess(true);
					result.setResultCode(ShopConstants.RESULT_CODE_SUCCESS);
					result.setMsg("成功更改优惠券状态！");
				} else {
					result.setSuccess(false);
					result.setResultCode(ShopConstants.RESULT_CODE_FALSE);
					result.setMsg("改变状态失败！");

				}

			}else {
				result.setSuccess(false);
				result.setResultCode(ShopConstants.RESULT_CODE_FALSE);
				result.setMsg("优惠券状态有误，无法操作！");
			}
		} else {
			result.setSuccess(false);
			result.setResultCode(ShopConstants.RESULT_CODE_FALSE);
			result.setMsg("未查询到此优惠券！");

		}

		return result;
	}
	
	/**
	 * @Method: getCouponDetail
	 * @Description 优惠券详情
	 * @param token
	 * @param couponId 优惠券id
	 * @return 
	 * @author liuziyu liuziyuwri@foxmail.com
	 * @date 2016年7月21日
	 * @see 
	 */
	@RequestMapping(value = "getCouponDetail")
	@ResponseBody
	public RequestJson getCouponDetail(String token, String couponId) {
		RequestJson result = new RequestJson();

		// 根据优惠券id查详情
		CouponInfo couponInfo = couponInfoService.selectByPrimaryKey(couponId);
		if (couponInfo != null) {
			result.setObj(couponInfo);
			result.setSuccess(true);
			result.setResultCode(ShopConstants.RESULT_CODE_SUCCESS);
			result.setMsg("成功查询优惠券详情！");
			
		} else {
			result.setSuccess(false);
			result.setResultCode(ShopConstants.RESULT_CODE_FALSE);
			result.setMsg("未查询到此优惠券！");

		}
		return result;
	}
	
	/**
	 * @Method: addCoupon
	 * @Description 新建优惠券
	 * @param token
	 * @param shopId 店铺id
	 * @param name 优惠券名称
	 * @param breakLine 满减条件
	 * @param breakPrice 面值
	 * @param beginDate 领取起始时间
	 * @param endDate 领取结束时间
	 * @param useBeginDate 使用起始时间
	 * @param useEndDate 使用结束时间
	 * @param countNumber 发放总量
	 * @return 
	 * @author liuziyu liuziyuwri@foxmail.com
	 * @date 2016年7月21日
	 * @see 
	 */
	@RequestMapping(value = "addCoupon")
	@ResponseBody
	public RequestJson addCoupon(String token, String shopId, String name,
			String breakLine, String breakPrice, String beginDate,
			String endDate, String useBeginDate, String useEndDate,
			Integer countNumber) {
		RequestJson result = new RequestJson();

		CouponInfo couponInfo = new CouponInfo();
		couponInfo.setId(UniqueNumberUtils.get18UniqueNumber());
		couponInfo.setName(name);
		couponInfo.setType(ShopConstants.COUPON_CUT_AT_CERTAIN_PRICE);
		couponInfo.setShopId(shopId);

		// 根据shopId查询cellId
		couponInfo.setCellId(shopInfoService.selectByPrimaryKey(shopId)
				.getCellId());
		BigDecimal breakLineBigDecimal = new BigDecimal(breakLine);
		BigDecimal breakPriceBigDecimal = new BigDecimal(breakPrice);
		couponInfo.setBreakLine(breakLineBigDecimal);
		couponInfo.setBreakPrice(breakPriceBigDecimal);
		couponInfo.setState(ShopConstants.COUPON_STATE_NOMAL);
		couponInfo.setBeginDate(beginDate);
		couponInfo.setEndDate(endDate);
		couponInfo.setCount(countNumber);

		CommonToken commonToken = commonTokenService.selectByToken(token);
		// 根据token查询登录名
		String loginname = commonToken.getAccount();
		couponInfo.setUserAccount(loginname);
		couponInfo.setUserAccountType(ShopConstants.SHOP_ACCOUNT_TYPE);
		couponInfo.setCreateTime(DateUtils.gettimestamp());

		// 随机生成16位数字作为优惠券的编码
		couponInfo.setCode(UniqueNumberUtils.get16UniqueNumber());
		couponInfo.setUseBeginDate(useBeginDate);
		couponInfo.setUseEndDate(useEndDate);

		int state = couponInfoService.insert(couponInfo);
		if (state == ShopConstants.INSERT_SUCCESS) {
			result.setObj(couponInfo);
			result.setSuccess(true);
			result.setResultCode(ShopConstants.RESULT_CODE_SUCCESS);
			result.setMsg("成功增加优惠券！");
		} else {
			result.setSuccess(false);
			result.setResultCode(ShopConstants.RESULT_CODE_FALSE);
			result.setMsg("新增优惠券失败！");

		}

		return result;
	}
	
	/**
	 * @Method: getCouponUsedList
	 * @Description  优惠券领用使用列表
	 * @param token
	 * @param couponId 优惠券id
	 * @param state 类型（ 1领用列表 2使用列表）
	 * @param pNo 分页
	 * @return 
	 * @author liuziyu liuziyuwri@foxmail.com
	 * @date 2016年7月22日
	 * @see 
	 */
	@RequestMapping(value = "getCouponUsedList")
	@ResponseBody
	public RequestJson getCouponUsedList(String token, String couponId,
			Integer state, Integer pNo) {
		RequestJson result = new RequestJson();

		// 指定默认为首页
		if (pNo == null || pNo < ShopConstants.PAGE_NO) {
			pNo = ShopConstants.PAGE_NO;
		}

		// 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
		PageHelper.startPage(pNo, ShopConstants.PAGE_SIZE);

		if (state == ShopConstants.COUPON_GET_LIST || state == ShopConstants.COUPON_USE_LIST) {
			// 根据优惠券id和类型查询列表（按结束时间降序）
			Map<String, Object> map = new HashMap<>();
			map.put("couponId", couponId);
			map.put("state", state);
			try {
				List<CouponDetail> couponDetail = couponDetailService.getCouponUsedList(map);
				
				// 分页
				PageInfo<CouponDetail> couponDetailP = new PageInfo<CouponDetail>(couponDetail);
				
				// 获取领取的人数
				Integer listNumber = couponDetail.size();
				Map<String, Object> resultMap = new HashMap<>();
				resultMap.put("listNumber", listNumber);
				resultMap.put("couponDetail", couponDetailP);
				
				result.setObj(resultMap);
				result.setSuccess(true);
				result.setResultCode(ShopConstants.RESULT_CODE_SUCCESS);
				result.setMsg("成功查询优惠券领用/使用情况！");
				
			} catch (Exception e) {
				e.printStackTrace();
				result.setSuccess(false);
				result.setResultCode(ShopConstants.RESULT_CODE_FALSE);
				result.setMsg("查询优惠券领用/使用情况失败！");
			}
			
		} else {
			result.setSuccess(false);
			result.setResultCode(ShopConstants.RESULT_CODE_FALSE);
			result.setMsg("state只能为1或2！");

		}
		return result;
	}
	
	/**
	 * @Description 上传图片接口 <br>
	 *              1、…<br>
	 *              2、…<br>
	 * 
	 * @param token
	 * @return
	 * @author caiyinli 13277030520@163.com
	 * @date 2016年7月7日
	 * @see
	 */
	@RequestMapping(value = "uploadShopPic", method = RequestMethod.POST)
	@ResponseBody
	public RequestJson uploadShopPic(String token, HttpServletRequest req,
			String shopId) throws FileNotFoundException {

	    RequestJson result = new RequestJson();
	    
	    OSSClient client = new  OSSClient(endpoint,accessId,accessKey); 
//      res.setContentType("text/html");
      final UploadFileItem[] uploadFiles = FileUploadUtil.saveUploadFile(req);

      File file = uploadFiles[0].getInternalFile();

    //图片上传至阿里云服务器
      Map<String, Object> returnmap = AliyunOssUtil.uploadFile(client,bucketName, file.getName(),file); 
      String fileUrl = (String)returnmap.get("objectkey");

        // 通过token获取用户信息
        CommonToken tokenInfo = commonTokenService.selectByToken(token);
        String loginname = tokenInfo.getAccount();
        User user = userService.selectByLoginName(loginname);

        if (user != null) {
            //查出该店铺相关信息并更新
        	ShopInfo shopInfo = shopInfoService.selectByPrimaryKey(shopId);
        	shopInfo.setLogo(fileUrl);
        	int flag = shopInfoService.update(shopInfo);
        	if (flag == Constants.SQL_RESULT_SUCCESS) {
        		result.setResultCode(ShopConstants.RESULT_CODE_SUCCESS);
        		result.setMsg("图片上传成功！");
        		result.setObj(fileUrl);
        	} else {
        		result.setResultCode(ShopConstants.RESULT_CODE_FALSE);
        		result.setMsg("图片上传失败！");
        	}
        }

		return result;

	}
}
